import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:device_info/device_info.dart';
import 'package:fate_blind_box/chat_pages/chat_message_list/logic.dart';
import 'package:fate_blind_box/chat_pages/chat_message_list/view.dart';
import 'package:fate_blind_box/chat_pages/meet_address_book/view.dart';
import 'package:fate_blind_box/chat_pages/meet_home/view.dart';
import 'package:fate_blind_box/chat_pages/meet_mine/view.dart';
import 'package:fate_blind_box/config/event_bus.dart';
import 'package:fate_blind_box/config/event_keys.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/network/http_config.dart';
import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/widget/keep_alive_wrapper.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../theme/theme_color.dart';
import 'state.dart';

class PersonHomeLogic extends GetxController
    with GetSingleTickerProviderStateMixin, WidgetsBindingObserver {
  final PersonHomeState state = PersonHomeState();

  List<BottomNavigationBarItem> bottomTab = [];

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: // 应用程序可见，前台
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        break;
      case AppLifecycleState.detached: // 申请将暂时暂停
        break;
      case AppLifecycleState.hidden: //应用程序当前处于隐藏状态
        break;
    }
  }

  @override
  void onInit() async {
    super.onInit();
    WidgetsBinding.instance.addObserver(this); //添加观察者
    state.pageController =
        PageController(initialPage: state.currentIndex.value);
    state.pageList = <Widget>[
      const KeepAliveWrapper(
        child: MeetHomePage(),
      ),
      const KeepAliveWrapper(child: ChatMessageListPage()),
      // const KeepAliveWrapper(child: MeetBlindBoxPage()),
      const KeepAliveWrapper(child: MeetAddressBookPage()),
      const KeepAliveWrapper(child: MeetMinePage()),
    ];
    initBottomTab();
  }

  Future<int> initData() async {
    return EMClient.getInstance.chatManager.getUnreadMessageCount();
  }

  /// 组合tabBar
  initBottomTab() {
    bottomTab = [
      BottomNavigationBarItem(
          icon: Image.asset(
            'images/ic_hhn.png',
            width: 22,
            height: 22,
          ),
          activeIcon: Image.asset(
            'images/ic_hhn.png',
            width: 22,
            height: 22,
            color: ThemeColor.colorD88E4B,
          ),
          label: '商圈'),
      BottomNavigationBarItem(
        icon: Badge(
          label: Text('${state.unreadCount.value}'),
          child: Image.asset(
            'images/ic_hxn.png',
            width: 22,
            height: 22,
          ),
          isLabelVisible: state.hasUnreadMessage.value,
        ),
        activeIcon: Badge(
          label: Text('${state.unreadCount.value}'),
          child: Image.asset(
            'images/ic_hxn.png',
            width: 22,
            height: 22,
            color: ThemeColor.colorD88E4B,
          ),
          isLabelVisible: state.hasUnreadMessage.value,
        ),
        label: '消息',
      ),
      // BottomNavigationBarItem(
      //     icon: Image.asset(
      //       'images/ic_hmn.png',
      //       width: 22,
      //       height: 22,
      //     ),
      //     activeIcon: Image.asset(
      //       'images/ic_hmc.png',
      //       width: 22,
      //       height: 22,
      //     ),
      //     label: '遇见'),
      BottomNavigationBarItem(
          icon: Image.asset(
            'images/ic_hln.png',
            width: 22,
            height: 22,
          ),
          activeIcon: Image.asset(
            'images/ic_hln.png',
            width: 22,
            height: 22,
            color: ThemeColor.colorD88E4B,
          ),
          label: '通讯录'),
      BottomNavigationBarItem(
          icon: Image.asset(
            'images/ic_hwn.png',
            width: 22.w,
            height: 22.w,
          ),
          activeIcon: Image.asset(
            'images/ic_hwn.png',
            width: 22.w,
            height: 22.w,
            color: ThemeColor.colorD88E4B,
          ),
          label: '我的')
    ];
  }

  /// 刷洗消息列表
  initRefresh() {
    final ChatMessageListLogic logic = Get.find<ChatMessageListLogic>();
    logic.onRefresh();
  }

  /// 邀请码
  checkInvite() async {
    String inviteCode = await Provider.getCache("inviteCode");
    final userId = Provider.memberId;
    String token = HttpConfig.token;
    if (inviteCode.isNotEmpty && userId.isNotEmpty && token.isNotEmpty) {
      await Api.getInstance().invite(userId, inviteCode);
      Provider.getUserEaseName().then((value) {
        state.username = value;
      });
    }
  }

  /// 根据状态码 判断是否要隐藏某些功能
  void hiddenPayLogic() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
    var type = await deviceModel;
    var res = await HttpRequest.request('member/version/isPay', params: {
      'istep': version,
      'versionType': type,
    });
    LogUtil.e('参数:$type====$version====$res');
    if (res['code'] == 0) {
      CommonConfig.isHiddenOpen = res['data'] ?? 1;
    }
  }

  /// 获取手机型号
  Future<String> get deviceModel async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      LogUtil.e('制造商:${androidInfo.manufacturer}');
      return androidInfo.manufacturer.toLowerCase();
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      String model = iosInfo.model;
      if (kDebugMode) {
        print('iOS 手机型号：$model');
      }
      return 'apple';
    }
    return '';
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    WidgetsBinding.instance.removeObserver(this); //添加观察者
    EventBus.instance.removeListener(eventName: EventKeys.chatUpdateBadge);
    state.tabController?.dispose();
  }
}
